<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;

class SessionsController extends Controller
{
    public function __construct()
    {
        // 已登录。。。不再登录
        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    public function create()
    {
        return view('sessions.create');
    }

    public function store(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email|max:255',
            'password' => 'required|min:6',
        ]);

        if (Auth::attempt($credentials, $request->has('remember'))){
            if (!Auth::user()->activated){
                Auth::logout();
                session()->flash('warning', '您的账户未激活，请检查邮箱中的注册邮件进行激活。');
                return back();
            }

            session()->flash('success', '欢迎回来！');
            return redirect()->route('users.show', Auth::id());
        }

        session()->flash('danger', '很抱歉，您的邮箱和密码不匹配');
        return back();
    }

    public function destroy()
    {
        Auth::logout();
        session()->flash('success', '您已成功退出！');
        return redirect()->route('login');
    }
}
